package com.ai.controller.made.ai_api;


import com.ai.annotation.EnterPathParamLog;
import com.ai.common.CommonResponse;


import com.ai.entity.alarm.AlgorithmAlarmBO;
import com.ai.entity.alarm.RecordAlarmPO;
import com.ai.model.param.AlgorithmAlarmParam;
import com.ai.service.made.RecordAlarmService;
import com.ai.service.rocketMq.RocketMQProducerService;
import com.ai.util.GetCameraPlaybackUrlUtil;
import com.ai.util.GetCameraPreviewURLUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 算法相关接口
 */
@RestController
@RequestMapping("/algorithmAPI/record")
@Slf4j
public class RecordAPI {

    @Resource
    RecordAlarmService recordAlarmService;

    @Autowired
    RocketMQProducerService rocketMQProducerService;


    @PostMapping("/addAlarm")
    @ApiOperation(value = "算法提交识别警告")
    @EnterPathParamLog
    public CommonResponse addAlarm( @ApiParam @RequestBody AlgorithmAlarmParam algorithmAlarmParams) {
        long l = System.currentTimeMillis();
        CommonResponse CommonResponse = recordAlarmService.addWarningRecord(algorithmAlarmParams);

        return CommonResponse;
    }


    @PostMapping("/getCameraPreviewUrl")
    @ApiOperation(value = "获取摄像头取流地址")
    @EnterPathParamLog
    public CommonResponse getCameraPreviewUrl(@ApiParam @RequestParam String cameraIndex) {

        String previewURL = GetCameraPreviewURLUtil.getCameraRtspUrl(cameraIndex,0);
        log.info("===========================  取流地址：{}  ===========================",previewURL);
        return CommonResponse.ok(previewURL);
    }

    @PostMapping("/getCameraStatus")
    @ApiOperation(value = "获取摄像头状态")
    @EnterPathParamLog
    public CommonResponse getCameraStatus(@ApiParam @RequestParam List<String> cameraIndex) {

        Map<String, Object> res = GetCameraPreviewURLUtil.getCameraStatusMap(cameraIndex);
        log.info("===========================  接口返回参数：{}  ===========================",res);
        return CommonResponse.ok(res);
    }

    @PostMapping("/getCameraPlaybackUrl")
    @ApiOperation(value = "获取摄像头取流地址")
    @EnterPathParamLog
    public CommonResponse getCameraPlaybackUrl(@ApiParam @RequestParam String recordId) {

        return recordAlarmService.getCameraPlaybackUrl(recordId);


    }

    @PostMapping("/getRedirectPreviewUrl")
    @ApiOperation(value = "获取重定向之后的取流地址")
    @EnterPathParamLog
    public CommonResponse getRedirectPreviewUrl(@ApiParam @RequestParam String previewUrl) {
        String redirectedUrl="";
        try {
            URL url = new URL(previewUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(false); // 禁止自动处理重定向
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode >= 300 && responseCode < 400) {
                 redirectedUrl = connection.getHeaderField("Location");
                log.info("===========================  重定向后的地址：{} ===========================",redirectedUrl);
            } else {
                log.info("===========================  没有重定向：{} ===========================",redirectedUrl);
            }
        } catch (Exception e) {
            log.error("===========================  原rtsp地址链接错误  ===========================");
            log.error(e.getMessage(),e);
        }
        return CommonResponse.ok(redirectedUrl);
    }


    @PostMapping("/testRocketMq")
    @ApiOperation(value = "mq测试")
    @EnterPathParamLog
    public CommonResponse testRocketMq() {
        List<RecordAlarmPO> recordAlarmPOList = recordAlarmService.list(new QueryWrapper<RecordAlarmPO>().between("id",1,4));

        if (CollectionUtils.isNotEmpty(recordAlarmPOList)){
            for (RecordAlarmPO recordAlarmPO : recordAlarmPOList) {
                Integer functionType = recordAlarmPO.getFunctionType();
                rocketMQProducerService.asyncSendMsg(JSONObject.toJSONString(recordAlarmPO), String.valueOf(functionType),null);
            }

        }

        return CommonResponse.ok("消息投递成功");
    }

}
